package finalproject.mobapp.Main;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import finalproject.mobapp.R;
import finalproject.mobapp.HttpRequestController.CustomHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EditPoiLocationActivity extends Activity {
	public static final String PREF_NAME = "SHARED_PREFERENCES";
	public static SharedPreferences prefs;
	
	LocationManager locationManager;
	boolean gps_enabled = false;
    boolean network_enabled = false;
    Timer timer1;
	
	JSONArray jArray;
	List<String> poiList;
	String poi_title_selected = null;
	int user_id;
	double latitude = 0;
	double longitude = 0;
	
	TextView result_location;
	Button retrievelocation_btn;
	Spinner poi_spinner;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editpoilocation);
        
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        result_location = (TextView) findViewById(R.id.result_location);
        poi_spinner = (Spinner) findViewById(R.id.poi_spinner);
        poiList = new ArrayList<String>();
        
        retrievelocation_btn = (Button) findViewById(R.id.retrievelocation_btn);
        retrievelocation_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				retrieveLocationHandle();
			}
		});
        
        prefs = this.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        user_id = prefs.getInt("user_id", 0);
        
        if (user_id != 0) {
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("user_id", String.valueOf(user_id)));
            
            String response = null;
            try {
				response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "getUserPoi", postParameters);
				jArray = new JSONArray(response);
				
				if (jArray != null) {
					JSONObject json_data = null;
					for (int i=0; i<jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String poi_title = json_data.getString("title");
						poiList.add(poi_title);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, poiList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        poi_spinner.setAdapter(adapter);
        poi_spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
    }
    
    public void retrieveLocationHandle() {
    	gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    	network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    	
    	if (gps_enabled) {
    		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    	}
    	
    	timer1 = new Timer();
    	timer1.schedule(new GetLastLocation(), 30000);
    }
    
    LocationListener locationListenerGps = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
			timer1.cancel();
			if (location != null) {
	    		latitude = location.getLatitude();
	    		longitude = location.getLongitude();
	    	}
			result_location.setText("Latitude : " + String.valueOf(latitude) + "\nLongitude : " + String.valueOf(longitude));
			locationManager.removeUpdates(locationListenerGps);
		}

		@Override
		public void onProviderDisabled(String provider) {}

		@Override
		public void onProviderEnabled(String provider) {}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {}
    	
    };
    
    class GetLastLocation extends TimerTask {
		@Override
		public void run() {
			//AddPoiActivity.this.findViewById(R.id.location).post(new Runnable() {
			result_location.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					locationManager.removeUpdates(locationListenerGps);
					
					Location gps_loc = null;
		    		Location net_loc = null;
		    		
		    		if (gps_enabled) {
		    			gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		    		}
		    		if (network_enabled) {
		    			net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		    		}
		    		
		    		if(gps_loc!=null && net_loc!=null){
		                if(gps_loc.getTime()>net_loc.getTime()) {
		                	Location location = gps_loc;
		                	latitude = location.getLatitude();
		    	    		longitude = location.getLongitude();
		                } else {
		                	Location location = net_loc;
		                	latitude = location.getLatitude();
		    	    		longitude = location.getLongitude();
		                }
		            } else if (gps_loc != null) {
		    			Location location = gps_loc;
		    			latitude = location.getLatitude();
			    		longitude = location.getLongitude();
		    		} else if (net_loc != null) {
		    			Location location = net_loc;
		    			latitude = location.getLatitude();
			    		longitude = location.getLongitude();
		    		}
		    		result_location.setText("Latitude : " + String.valueOf(latitude) + "\nLongitude : " + String.valueOf(longitude));
				}
			});
		}
    }
    
    public void saveLocationHandle(View v) {
    	if (poi_title_selected!=null) {
			ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("user_id", String.valueOf(user_id)));
            postParameters.add(new BasicNameValuePair("poi_title", poi_title_selected));
            postParameters.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
            postParameters.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
            
            String response = null;
            try {
				response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "updatePoiLocation", postParameters);
				String res = response.toString();
				res.replaceAll("\\s+", "");
				if (res.equals("-1") || res.equals("0")) {
					Toast.makeText(getApplicationContext(), "update gagal", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getApplicationContext(), "update berhasil", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			Toast.makeText(getApplicationContext(), "poi title null", Toast.LENGTH_LONG).show();
		}
    }
    
    public void backHandle(View v) {
    	//Intent intent = new Intent();
    	//intent.setClass(this, MenuActivity.class);
    	
    	EditPoiLocationActivity.this.finish();
    	//startActivity(intent);
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View v, int pos,
				long id) {
			// TODO Auto-generated method stub
			poi_title_selected = parent.getItemAtPosition(pos).toString();
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
			
		}
    	
    }
}
